package com.zyx.shiro.shiro.realms;

import cn.hutool.extra.spring.SpringUtil;
import com.zyx.shiro.entity.Role;
import com.zyx.shiro.entity.User;
import com.zyx.shiro.service.IUserService;
import com.zyx.shiro.shiro.salt.MyByteSource;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.util.ObjectUtils;

import java.util.Collections;
import java.util.List;
import java.util.Optional;

/**
 * 自定义认证授权验证
 *
 * @author zyx
 * @since 2022/7/29 23:09
 */
@Slf4j
public class CustomerRealm extends AuthorizingRealm {

    /**
     * 在工厂中获取service对象
     */
    private final IUserService userService = SpringUtil.getBean("userService", IUserService.class);

    /**
     * 处理授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        // 获取用户名
        String principal = (String) principals.getPrimaryPrincipal();
        // 依据用户名查询角色及权限信息
        User user = userService.findRolesAndPermsByUserName(principal);
        // 设置角色及权限信息
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        List<Role> roles = user.getRoles();
        Optional.ofNullable(roles)
                .orElse(Collections.emptyList())
                .forEach(role -> {
                    // 添加角色信息
                    authorizationInfo.addRole(role.getName());
                    Optional.ofNullable(role.getPerms())
                            .orElse(Collections.emptyList())
                            // 添加权限信息
                            .forEach(perm -> authorizationInfo.addStringPermission(perm.getName()));
                });
        log.info("==================== 获取角色权限信息成功 ====================");
        return authorizationInfo;
    }

    /**
     * 处理认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        log.info("==================== CustomerRealm.doGetAuthenticationInfo ====================");
        // 根据身份信息
        String principal = (String) token.getPrincipal();
        User user = userService.findByUserName(principal);
        if (!ObjectUtils.isEmpty(user)) {
            return new SimpleAuthenticationInfo(
                    user.getUsername(),
                    user.getPassword(),
                    new MyByteSource(user.getSalt()),
                    // 使用原生的ByteSource工具创建的ByteSource反序列化有问题
                    // ByteSource.Util.bytes(user.getSalt()),
                    this.getName()
            );
        }
        return null;
    }

}
